﻿using PayrollHR.Web;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Payroll.BusinessLogic.CustomerManager;
using Payroll.Common;
using Payroll.Common.Utils;
using System.Drawing;
using System.IO;
using OfficeOpenXml;
using OfficeOpenXml.Style;
using System.Data;

namespace PayrollHR.Administration.Modules
{
    public partial class CustomerAttributeControl : BasePayrollAdministrationUserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.Bind(0);
            }
        }
        protected void FillDropDowns(DropDownList ddlPackageCode)
        {
            ddlPackageCode.Items.Clear();
            var packages = this.PackageService.GetAllPackage();
            foreach (var package in packages)
            {
                ListItem item2 = new ListItem(package.Name, package.PackCode);
                ddlPackageCode.Items.Add(item2);
            }
        }
        protected void btnFilter_Click(object sender, EventArgs e)
        {
            this.Bind(0);
        }

        protected void btnConfirm_Click(object sender, EventArgs e)
        {
            this.Confirm();
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            this.Delete();
        }
        #region Function
        protected void Confirm()
        {
            if (Page.IsValid)
            {
                int Row = gvCustomer.Rows.Count;
                string result = "";
                try
                {
                    foreach (GridViewRow row in gvCustomer.Rows)
                    {
                        var cbResultsId = row.FindControl("cbResultsId") as CheckBox;
                        bool isChecked = cbResultsId.Checked;
                        if (isChecked)
                        {
                            result += gvCustomer.DataKeys[row.RowIndex].Value + ",";
                        }
                    }
                    if (result.Length > 0)
                    {
                        result = result.Substring(0, result.Length - 1);
                        this.Bind(2, result);
                    }
                }
                catch (Exception ex)
                {
                    ProcessException(ex);
                }
            }
        }
        protected void Delete()
        {
            if (Page.IsValid)
            {
                int Row = gvCustomer.Rows.Count;
                string result = "";
                try
                {
                    foreach (GridViewRow row in gvCustomer.Rows)
                    {
                        var cbResultsId = row.FindControl("cbResultsId") as CheckBox;
                        bool isChecked = cbResultsId.Checked;
                        if (isChecked)
                        {
                            result += gvCustomer.DataKeys[row.RowIndex].Value + ",";
                        }
                    }
                    if (result.Length > 0)
                    {
                        result = result.Substring(0, result.Length - 1);
                        this.Bind(1, result);
                    }
                }
                catch (Exception ex)
                {
                    ProcessException(ex);
                }
            }
        }
        protected void Bind(int option, string result = null)
        {
            gvCustomer.DataSource = this.GetAllCustomer(option, result);           
            gvCustomer.DataBind();
        }
        protected List<CustomerAttribute> GetAllCustomer(int option, string result = null)
        {
            string Distributor = null;
            if (ttxDistributor.Text.Trim().Length > 0)
                Distributor = ttxDistributor.Text.Trim();
            string customerName = null;
            if (txtCustomerName.Text.Trim().Length > 0)
                customerName = txtCustomerName.Text.Trim();
            string taxcode = null;
            if (txtTaxCode.Text.Trim().Length > 0)
                taxcode = txtTaxCode.Text.Trim();
            string mobile = null;
            if (txtMobile.Text.Trim().Length > 0)
                mobile = txtMobile.Text.Trim();
            string regfrom = null;
            string to = null;
            string email = null;

            DateTime? fromdate = FromDatePicker.SelectedDate;
            if (!CommonHelper.IsNull(fromdate))
                regfrom = fromdate.Value.ToString("yyyy-MM-dd");
            DateTime? todate = ToDatePicker.SelectedDate;
            if (!CommonHelper.IsNull(todate))
                to = todate.Value.ToString("yyyy-MM-dd");

            int ResStatus = ckConfirm.Checked ? 0 : 1;
            int? Remain = CommonHelper.ToInteger(ddlRemain.SelectedItem.Value);
            if (Remain == 0)
                Remain = null;
            int count = ddlCount.SelectedIndex == -1 ? 100 : CommonHelper.ToInteger(ddlCount.SelectedItem.Value);
            if (count == -1)
                count = int.MaxValue;
            switch (option)
            {
                case 0:
                    return this.ResultService.GetCustomerDevices(Distributor: Distributor, customerName: customerName, taxcode: taxcode, mobile: mobile, email: email, Alert: Remain, ResStatus: ResStatus, pageIndex: 0, pageSize: count);
                    
                case 1:
                    return this.ResultService.Delete(ResultsId: result, Distributor: Distributor, customerName: customerName, taxcode: taxcode, mobile: mobile, email: email, Alert: Remain, ResStatus: ResStatus, pageIndex: 0, pageSize: count);
                    
                case 2:
                    return this.ResultService.Confirm(ResultsId: result, Distributor: Distributor, customerName: customerName, taxcode: taxcode, mobile: mobile, email: email, Alert: Remain, ResStatus: ResStatus, pageIndex: 0, pageSize: count);
                    
            }
            return new List<CustomerAttribute>();
        }
        #endregion

        protected void gvCustomer_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvCustomer.PageIndex = e.NewPageIndex;
            this.Bind(0);
        }

        protected void ddlCount_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.Bind(0);
        }

        protected void gvCustomer_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            //e.Row.Attributes.Add("style", "cursor:help;");
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                var hfAlert = e.Row.FindControl("hfAlert") as HiddenField;
                if (CommonHelper.ToInteger(hfAlert.Value) <= CommonHelper.ToInteger(ddlAlert.SelectedItem.Value))
                {
                    e.Row.BackColor = Color.FromName("Red"); 
                }
                if ((e.Row.RowState & DataControlRowState.Edit) > 0)
                {
                    var hdfPackageCode = e.Row.FindControl("hdfPackageCode") as HiddenField;
                    DropDownList ddlPackageCode = (DropDownList)e.Row.FindControl("ddlPackageCode");
                    this.FillDropDowns(ddlPackageCode);
                    ddlPackageCode.SelectedValue = hdfPackageCode.Value;
                }
            }
        }

        protected void ddlAlert_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.Bind(0);
        }

        protected void ddlRemain_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.Bind(0);
        }

        protected void ExportButton_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                try
                {
                    string fileName = string.Format("CustomerList_{0}", DateTime.Now.ToString("dd-MM-yyyy_HH.mm") + ".xlsx");
                    string fileInfo = Server.MapPath(@"..\Administration\FileExport\" + fileName);
                    FileInfo template = new FileInfo(Server.MapPath(@"..\Administration\Template\CustomerList.xlsx"));
                    FileInfo filewrite = template.CopyTo(fileInfo, true);
                    var List = this.GetAllCustomer(0);
                    this.WriteSheets(filewrite, List);
                    hlexport.Visible = true;
                    hlexport.Text = "Save As File Export";
                    hlexport.NavigateUrl = "../FileExport/" + fileName;
                }
                catch (Exception exc)
                {
                    ProcessException(exc);
                }
            }            
        }
        protected void WriteSheets(FileInfo filewrite, List<CustomerAttribute> List)
        {
            int aler = CommonHelper.ToInteger(ddlAlert.SelectedItem.Value);
            int MaxRow = List.Count;
            using (var xlsx = new ExcelPackage(filewrite))
            {
                ExcelWorksheet worksheet = xlsx.Workbook.Worksheets[1];
                if (MaxRow > 2)
                {
                    int i = 4;
                    worksheet.InsertRow(i, MaxRow - 2, i);
                    worksheet.Cells[1, 2].Value = string.Format("Danh sách khách hàng {0}", DateTime.Now.ToString("dd/MM/yyyy"));
                    foreach (var info in List)
                    {
                        worksheet.Cells[i, 1].Value = i - 3;
                        worksheet.Cells[i, 2].Value = info.Distributor;
                        worksheet.Cells[i, 3].Value = info.CustomerName;
                        worksheet.Cells[i, 4].Value = info.TaxCode;
                        worksheet.Cells[i, 5].Value = info.Address;
                        worksheet.Cells[i, 6].Value = info.Mobile;
                        worksheet.Cells[i, 7].Value = info.DatePurchase;
                        worksheet.Cells[i, 8].Value = info.EndDate;
                        worksheet.Cells[i, 9].Value = info.PackageCode;
                        worksheet.Cells[i, 10].Value = info.PackageTimeName;
                        worksheet.Cells[i, 11].Value = info.PackageTypeName;
                        this.Border(worksheet, i, 1, 7);
                        if (info.Alert <= CommonHelper.ToInteger(ddlAlert.SelectedItem.Value))
                        {
                            worksheet.Row(i).Style.Fill.PatternType = ExcelFillStyle.Solid;
                            worksheet.Row(i).Style.Fill.BackgroundColor.SetColor(Color.Red);
                        }
                        i += 1;
                    }
                }
                xlsx.Save();
            }
        }
        protected void Border(ExcelWorksheet worksheet, int row, int Colfrom, int ColTo)
        {
            for (int i = Colfrom; i <= ColTo; i++)
            {
                var cell = worksheet.Cells[row, i];
                var border = cell.Style.Border;
                border.Bottom.Style =
                    border.Top.Style =
                    border.Left.Style =
                    border.Right.Style = ExcelBorderStyle.Thin;
            }
        }

        protected void gvCustomer_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            try
            {
                GridViewRow row = (GridViewRow)gvCustomer.Rows[e.RowIndex];
                int ResultsId = CommonHelper.ToInteger(gvCustomer.DataKeys[row.RowIndex].Value);
                TextBox txtCustomerName = (TextBox)row.FindControl("txtCustomerName");
                TextBox txtTaxCode = (TextBox)row.FindControl("txtTaxCode");
                TextBox txtAddress = (TextBox)row.FindControl("txtAddress");
                TextBox txtMobile = (TextBox)row.FindControl("txtMobile");
                TextBox txtDatePurchase = (TextBox)row.FindControl("txtDatePurchase");
                DropDownList ddlPackageCode = (DropDownList)row.FindControl("ddlPackageCode");
                Results result = new Results
                {
                    ResultsId = ResultsId,
                    CustomerName = txtCustomerName.Text.Trim(),
                    TaxCode = txtTaxCode.Text.Trim(),
                    Address = txtAddress.Text.Trim(),
                    Mobile = txtMobile.Text.Trim(),
                    DatePurchase = txtDatePurchase.Text.Trim(),
                    PackageCode = ddlPackageCode.SelectedItem.Value
                };
                this.ResultService.SaveCustomer(result);
                gvCustomer.EditIndex = -1;
                this.Bind(0);
            }
            catch (Exception ex) {
                Page.ClientScript.RegisterStartupScript(GetType(), "Message", "<SCRIPT LANGUAGE='javascript'>alert('" + ex.Message.ToString().Replace("'", "") + "');</script>");
            }
        }

        protected void gvCustomer_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            gvCustomer.EditIndex = -1;
            this.Bind(0);
        }

        protected void gvCustomer_RowEditing(object sender, GridViewEditEventArgs e)
        {
            gvCustomer.EditIndex = e.NewEditIndex;
            this.Bind(0);
        }
    }
}